package com.rh.controller;

import com.rh.exception.EducationException;
import com.rh.result.ResultVo;
import com.rh.service.MsmService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/edumsm/msm")
@Api(tags = "邮件发送验证码服务")
public class MsmController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 获取邮箱验证码
     */
    @ApiOperation(value = "1.发送验证码")
    @GetMapping("send/{mobile}")
    public ResultVo sendCode(@PathVariable String mobile){
        //校验邮箱
        if(StringUtils.isEmpty(mobile)){
            throw new EducationException(2001,"邮箱不能为空");
        }
        Boolean aBoolean = checkEmail(mobile);
        if(!aBoolean){
            throw new EducationException(20001,"邮箱格式不正确");
        }
        //先从redis中获取验证码，如果有的话就直接返回
        String redisCode=redisTemplate.opsForValue().get(mobile);
        if(!StringUtils.isEmpty(redisCode)){
            return ResultVo.ok();
        }
        //如果redis获取不到,就发送邮件获取
        String code=msmService.sendCode(mobile);
        if (StringUtils.isEmpty(code)){
            return ResultVo.error().message("验证码为空");
        }
        //存入redis，并设置过期时间
        redisTemplate.opsForValue().set(mobile,code,5, TimeUnit.MINUTES);
        return ResultVo.ok();
    }

    /**
     * 校验邮箱格式的正则
     */
    public static  Boolean checkEmail(String email){
        String pattern = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(email);
        return m.matches();
    }
}
